/*
 * ========================================================
 * Copyright(c) 2014 杭州偶尔科技-版权所有
 * ========================================================
 * 本软件由杭州偶尔科技所有, 未经书面许可, 任何单位和个人不得以
 * 任何形式复制代码的部分或全部, 并以任何形式传播。
 * 公司网址
 * 
 * 			http://www.kkkd.com/
 * 
 * ========================================================
 */
package com.simon.mengkou.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.StringRes;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Toast;

import com.ouertech.android.agm.lib.base.future.core.AgnettyResult;
import com.ouertech.android.agm.lib.base.utils.UtilDate;
import com.ouertech.android.agm.lib.base.utils.UtilDevice;
import com.ouertech.android.agm.lib.base.utils.UtilLog;
import com.ouertech.android.agm.lib.base.utils.UtilNetwork;
import com.ouertech.android.agm.lib.base.utils.UtilString;
import com.ouertech.android.agm.lib.ui.widget.toast.CustomTxtToast;
import com.simon.mengkou.R;
import com.simon.mengkou.future.base.OuerException;
import com.simon.mengkou.future.base.OuerFutureListener;
import com.simon.mengkou.future.base.OuerHeader;
import com.simon.mengkou.system.constant.CstOuer;
import com.simon.mengkou.system.global.OuerApplication;
import com.tencent.mid.api.MidCallback;
import com.tencent.mid.api.MidService;

import java.text.DecimalFormat;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

/**
 * @author : Zhenshui.Xia
 * @date : 2015/7/3.
 * @desc : 应用常用工具类
 */
public class UtilOuer {
    private static OuerHeader mHeaderInfo;
    private static final String UNKNOWN = "unknown";

    //时间单位定义
    public static final long SECOND     = 1 		* 1000L;
    public static final long MINUTE     = SECOND * 60;
    public static final long HOUR       = MINUTE * 60;
    public static final long DAY        = HOUR 	* 24;
    public static final long WEEK       = DAY 	* 7;

    private static final String MONTHS[] = {"Jan", "Feb", "Mar",
            "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};

    /**
     * 获取当前项目的应用名
     * @param context
     * @return
     */
    public static String getAppName(Context context) {
        PackageManager pm = context.getPackageManager();
        String name = context.getApplicationInfo().loadLabel(pm).toString();
        return name;
    }

    /**
     * 获取当前运行的进程名
     *
     * @param context
     * @return
     */
    public static String getProcessName(Context context) {
        int pid = android.os.Process.myPid();
        ActivityManager am = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo process : am.getRunningAppProcesses()) {
            if (process.pid == pid) {
                return process.processName;
            }
        }

        return null;
    }


    /**
     * 获取当前运行界面的包名
     *
     * @param context
     * @return
     */
    public static String getTopPackageName(Context context) {
        ActivityManager am = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
        return cn.getPackageName();
    }

    /**
     * 获取当前运行界面的activity名
     * @param context
     * @return
     */
    public static String getTopActivity(Context context) {
        ActivityManager am = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
        return cn.getClassName();
    }

    /**
     * 获取清单指定meta key的值
     * @param key
     * @return
     */
    public static String getMetaValue(Context context, String key) {
        String metaValue = "";
        try {
            ApplicationInfo appInfo = context.getPackageManager()
                    .getApplicationInfo(context.getPackageName(),
                            PackageManager.GET_META_DATA);
            metaValue = appInfo.metaData.getString(key);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return metaValue;
    }

    /**
     * 获取当前的应用渠道
     * @param context
     * @return
     */
    public static String getAppChannel(Context context	) {
        String channel = getMetaValue(context, CstOuer.CHANNEL_META);

        if(UtilString.isBlank(channel)) {
            channel = CstOuer.PROJECT;
        }

        return channel;
    }

    /**
     * 获取系统ua信息
     * @return
     */
    public static String getWebUA(Context context) {
        String ua = null;
        WebView webview = new WebView(context);
        WebSettings settings = webview.getSettings();
        ua = settings.getUserAgentString();
        return ua;
    }


    /**
     * 获取本地语言
     *
     * @return
     */
    public static String getLocale() {
        Locale locales = Locale.getDefault();
        // 格式化语言类型
        StringBuilder format = new StringBuilder(locales.getLanguage())
                .append("-")
                .append(locales.getCountry());
        return format.toString();
    }


    /**
     * 获取版本号
     * @return
     */
    public static int getVersionCode(Context context) {
        int code = 0;
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            code = pi.versionCode;
        } catch(Exception ex) {
            ex.printStackTrace();
        }

        return code;
    }

    /**
     * 获取版本名
     * @return
     */
    public static String getVersionName(Context context) {
        String name = "";
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            name = pi.versionName;
        } catch(Exception ex) {
            name = "unknown";
        }

        return name;
    }

    /**
     * 获取统计信息
     * @param ctx
     * @return
     */
    public static OuerHeader getOuerHeader(Context ctx) {
        if(mHeaderInfo != null) {
            return mHeaderInfo;
        }

        mHeaderInfo = new OuerHeader();
        if (UtilString.isBlank(Build.MANUFACTURER)) {
            mHeaderInfo.setManufacturer(UNKNOWN);
        } else {
            mHeaderInfo.setManufacturer(Build.MANUFACTURER);
        }

        if (UtilString.isBlank(Build.MODEL)) {
            mHeaderInfo.setModel(UNKNOWN);
        } else {
            mHeaderInfo.setModel(Build.MODEL);
        }

        mHeaderInfo.setSdk((short) Build.VERSION.SDK_INT);
        mHeaderInfo.setClient("Android" + Build.VERSION.RELEASE);
        mHeaderInfo.setDevice(UtilDevice.isTablet(ctx) ? "pad" : "phone");
        mHeaderInfo.setVersionCode(getVersionCode(ctx));
        mHeaderInfo.setVersionName(getVersionName(ctx));
        mHeaderInfo.setAppChannel(getAppChannel(ctx));

        String imei = UtilDevice.getImei(ctx);
        if(UtilString.isBlank(imei)) {
            imei = UNKNOWN;
        }
        mHeaderInfo.setImei(imei);

        String osId = UtilDevice.getAndroidID(ctx);
        if(UtilString.isBlank(osId)) {
            osId = UNKNOWN;
        }
        mHeaderInfo.setOsId(osId);

        String mac = UtilDevice.getMAC(ctx);
        if(UtilString.isBlank(mac)) {
            mac = UNKNOWN;
        }
        mHeaderInfo.setMac(mac);

        String deviceId = MidService.getMid(ctx);
        if("0".equals(deviceId)) {
            MidService.requestMid(ctx, new MidCallback() {
                @Override
                public void onSuccess(Object data) {
                    mHeaderInfo.setDeviceId((String) data);
                }

                @Override
                public void onFail(int errCode, String msg) {

                }
            });
        } else {
            mHeaderInfo.setDeviceId(deviceId);
        }

        UtilDevice.Device device = UtilDevice.getDevice(ctx);
        mHeaderInfo.setSize(device.getWidth() + "x" + device.getHeight());

        mHeaderInfo.setNetType(UtilNetwork.getNetworkType(ctx).getValue());
        mHeaderInfo.setApnType(UtilNetwork.getApnType(ctx).getValue());
        mHeaderInfo.setIpAddress(UtilNetwork.getIpAddress(ctx));

        UtilLog.d(mHeaderInfo.toString());

        return mHeaderInfo;
    }


    /**
     * 显示Toast
     *
     * @param context
     * @param resId
     */
    public static void toast(Context context, @StringRes int resId) {
        toast(context, context.getString(resId), Toast.LENGTH_SHORT);
    }

    /**
     * 显示Toast
     *
     * @param context
     * @param text
     */
    public static void toast(Context context, String text) {
        toast(context, text, Toast.LENGTH_SHORT);
    }

    /**
     * 显示Toast
     *
     * @param context
     * @param resId
     * @param duration
     */
    public static void toast(Context context, @StringRes int resId, int duration) {
        toast(context, context.getString(resId), duration);
    }

    /**
     * 显示Toast
     *
     * @param context
     * @param text
     * @param duration
     */
    public static void toast(Context context, String text, int duration) {
        //系统文本toast显示
        //SystemTxtToast.show(context, text, duration);

        //自定义文本toast显示
        CustomTxtToast.show(context, text, duration);
    }

    /**
     * 格式化价格
     * @param price
     */
    public static String formatPrice(double price) {
        return new DecimalFormat("######0.00").format(price);
    }

    /**
     * 格式化时间
     * @param time
     * @return
     */
    public static String formatDate(long time) {
        return UtilDate.formatDate(time, "yyyy-MM-dd HH:mm:ss");
    }

    /**
     * 格式化时间
     * @param time
     * @return
     */
    public static String formatDate2(long time) {
        final Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(time);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        return day + MONTHS[month];
    }


    /**
     * 隐藏输入面板
     * @param activity
     */
    public static void hideInputManager(Activity activity) {
        InputMethodManager imm = (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive()) {
            View view = null;
            if (null != (view = activity.getCurrentFocus())) {
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
            }
        }
    }


    /**
     * 显示输入面板
     * @param activity
     */
    public static void showInputManager(final Activity activity) {
        OuerApplication.mOuerFuture.delay(500,
                new OuerFutureListener(activity){

                    @Override
                    public void onComplete(AgnettyResult result) {
                        super.onComplete(result);
                        InputMethodManager imm = (InputMethodManager)activity
                                .getSystemService(Context.INPUT_METHOD_SERVICE);
                        View view = null;

                        if (null != (view = activity.getCurrentFocus())) {
                            imm.showSoftInput(view, 0);
                        }
                    }

                });
    }


    /**
     * 获取指定格式的字符串
     * @param s 时间戳
     * @param format 时间格式化
     * @return
     */
    public static String getFormatDate(Context ctx, long s, String format){
        if(s==0) return "";
        String str = "";
        try{
            str = UtilDate.formatDate(s, format);
            long now = System.currentTimeMillis();
            long ts = now-s;
            if(ts < HOUR){
                int min = (int)(ts/MINUTE);
                if(min <= 5){
                    str = ctx.getString(R.string.common_time_just_now);
                }else{
                    str = ctx.getString(R.string.common_time_min_before, min);
                }
            } else if(ts >= HOUR && ts < DAY){ //当天
                int h = (int)(ts/HOUR);
                str = ctx.getString(R.string.common_time_hour_before, h);
            }else if(ts >= DAY && ts < 2*DAY){ //昨天
                str = ctx.getString(R.string.common_time_yesterday);
            }else if(ts >= 2*DAY && ts < WEEK){ //本周
                int day = (int)(ts/DAY);
                str = ctx.getString(R.string.common_time_day_before, day);
            }else if(ts > WEEK){ //超过一周的情况
                str = UtilDate.formatDate(s,format);
            }
        }catch(Exception e){
            UtilLog.e(e.getLocalizedMessage());
        }

        return str;
    }

    /**
     * 格式化倒计时
     * @param time
     * @return
     */
    public static String formatCounterTime(long time) {
        long hour = time / HOUR;
        long minute = (time - hour * HOUR) / MINUTE;
        long second = (time - hour * HOUR - minute * MINUTE) / SECOND;
        StringBuilder sb = new StringBuilder();
        if(hour < 10) {
            sb.append("0").append(hour).append(":");
        } else {
            sb.append(hour).append(":");
        }

        if(minute < 10) {
            sb.append("0").append(minute).append(":");
        } else {
            sb.append(minute).append(":");
        }

        if(second < 10) {
            sb.append("0").append(second);
        } else {
            sb.append(second);
        }

        return sb.toString();
    }

    /**
     *
     * @param count
     * @return
     */
    public static String formatNum(Context context, int count) {
        if(count < 10000) {
            return String.valueOf(count);
        } else {
            int mod = count % 10000;
            if(mod < 1000) {
                return context.getString(R.string.common_num, count / 10000);
            } else {
                String value = new DecimalFormat("###.0").format(count / 10000f);
                return context.getString(R.string.common_num, value);
            }
        }
    }

    /**
     *
     * @param context
     * @param stringRes
     */
    public static void showExceptionToast(Context context, AgnettyResult result , int stringRes) {
        Exception ex = result.getException();
        if (ex instanceof OuerException) {
            UtilOuer.toast(context, ex.getMessage());
        }else {
            UtilOuer.toast(context, stringRes);
        }
    }


}
